﻿#include "Curve2DPlotor.h"
#include "qcustomplot.h"
#include "LineChartTracer.h"
#include "LineChartStraightLine.h"
#include <algorithm>
#include "PolarGraph.h"

#include "BaseWidget/IWidgetSignal.h"

namespace pst
{
    Curve2DPlotor::Curve2DPlotor(QWidget* parent)
        : QCustomPlot(parent)

    {
        m_isShowPreviewTracer = false;
        m_previewTracer = new LineChartTracer(this);
        m_previewTracer->SetOnlyShowTracer(true);
        m_previewTracer->setVisible(false);
        this->installEventFilter(this);
        //设置文字默认值
        setXAxisFontSize(20);
        setYAxisFontSize(20);
        std::srand(QDateTime::currentDateTime().toMSecsSinceEpoch() / 1000.0);

        this->setInteractions(QCP::Interactions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes |
                                                QCP::iSelectLegend | QCP::iSelectPlottables | QCP::iMultiSelect | QCP::iSelectItems));
        this->setMultiSelectModifier(Qt::ControlModifier);
        this->xAxis->setRange(-8, 8);
        this->yAxis->setRange(-5, 5);
        this->axisRect()->setupFullAxesBox();

        this->plotLayout()->insertRow(0);
        QCPTextElement* title = new QCPTextElement(this, "二维图", QFont("sans", 10, QFont::Bold));
        this->plotLayout()->addElement(0, 0, title);

        this->xAxis->setLabel("x 轴");
        this->yAxis->setLabel("y 轴");
        this->legend->setVisible(false);
        QFont legendFont = font();
        legendFont.setPointSize(20);
        this->legend->setFont(legendFont);
        this->legend->setSelectedFont(legendFont);
        // this->legend->setSelectableParts(QCPLegend::spNone); //不允许选择图例中的项

        this->rescaleAxes();

        // connect slot that ties some axis selections together (especially opposite axes):
        connect(this, SIGNAL(selectionChangedByUser()), this, SLOT(selectionChanged()));
        // connect slots that takes care that when an axis is selected, only that direction can be dragged and zoomed:
        connect(this, SIGNAL(mousePress(QMouseEvent*)), this, SLOT(slot_mousePress()));
        connect(this, SIGNAL(mouseWheel(QWheelEvent*)), this, SLOT(mouseWheel()));

        // make bottom and left axes transfer their ranges to top and right axes:
        connect(this->xAxis, SIGNAL(rangeChanged(QCPRange)), this->xAxis2, SLOT(setRange(QCPRange)));
        connect(this->yAxis, SIGNAL(rangeChanged(QCPRange)), this->yAxis2, SLOT(setRange(QCPRange)));

        // connect some interaction slots:
        // connect(this, SIGNAL(axisDoubleClick(QCPAxis*, QCPAxis::SelectablePart, QMouseEvent*)), this, SLOT(axisLabelDoubleClick(QCPAxis*, QCPAxis::SelectablePart)));
        // connect(this, SIGNAL(legendDoubleClick(QCPLegend*, QCPAbstractLegendItem*, QMouseEvent*)), this, SLOT(legendDoubleClick(QCPLegend*, QCPAbstractLegendItem*)));
        // connect(title, SIGNAL(doubleClicked(QMouseEvent*)), this, SLOT(titleDoubleClick(QMouseEvent*)));

        // connect slot that shows a message in the status bar when a graph is clicked:
        // connect(this, SIGNAL(plottableClick(QCPAbstractPlottable*, int, QMouseEvent*)), this, SLOT(graphClicked(QCPAbstractPlottable*, int)));

        // setup policy and connect slot for context menu popup:
        this->setContextMenuPolicy(Qt::CustomContextMenu);
        connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuRequest(QPoint)));

        connect(this, &QCustomPlot::plottableClick, this, &Curve2DPlotor::onGraphClicked);
        connect(this, &QCustomPlot::legendClick, this, &Curve2DPlotor::onLegendClicked);

        connect(this, &QCustomPlot::beforeReplot, [this]()
                {
            if (m_lineArray.isEmpty()) {
                return;
            }
            for (auto lineChartStraightLine : m_lineArray) {
                lineChartStraightLine->slot_update();
            } });

        connect(IWidgetSignalInstance, &BaseWidget::IWidgetSignal::signal_exitAddMarkerState, this, &Curve2DPlotor::slot_exitAddMarkerState);
        
        connect(IWidgetSignalInstance, &BaseWidget::IWidgetSignal::signal_lineChartCurve2DPlotorRemoveSelectedGraph, this, [this]()
            { 
                if (!this->isVisible())
                        return;
                emit removeSelectedGraph();
            });
        connect(IWidgetSignalInstance, &BaseWidget::IWidgetSignal::signal_lineChartCurve2DPlotorRemoveAllGraphs, this, [this]()
            { 
                if (!this->isVisible())
                        return;
                emit removeAllGraphs(); 
            });
        connect(IWidgetSignalInstance, &BaseWidget::IWidgetSignal::signal_lineChartCenterWidgetMoveLegend, this, [this](int dataInt) {
            if (this->isVisible()) {
                this->axisRect()->insetLayout()->setInsetAlignment(0, (Qt::Alignment)dataInt);
                this->replot();
            }
            });

        connect(IWidgetSignalInstance, &BaseWidget::IWidgetSignal::signal_lineChartCreateLineChartStraightLine, this, [this](int typeAxis)
            { 

                    if (!this->isVisible())
                        return;
                    if (typeAxis==0)
                    {

                        slot_exitAddMarkerState();
                        m_isShowPreviewTracer = false;
                        m_previewTracer->setVisible(false);
                        auto xLine = new LineChartStraightLine(this, LineChartStraightLine::XAxis);
                        xLine->XAxisLineUpdate(this->xAxis->range().center());
                        xLine->updataStyle2DGuideLineProperty();
                        xLine->setLineChartStraightLineID(++m_lineChartStraightLineMaxID);
                        m_lineArray.append(xLine);
                        this->replot();
                    }
                    else if (typeAxis==1)
                    {
                        slot_exitAddMarkerState();
                        m_isShowPreviewTracer = false;
                        m_previewTracer->setVisible(false);
                        auto yLine = new LineChartStraightLine(this, LineChartStraightLine::YAxis);
                        yLine->YAxisLineUpdate(this->yAxis->range().center());
                        yLine->updataStyle2DGuideLineProperty();
                        yLine->setLineChartStraightLineID(++m_lineChartStraightLineMaxID);
                        m_lineArray.append(yLine);
                        this->replot(); 
                    }

            });

            connect(IWidgetSignalInstance, &BaseWidget::IWidgetSignal::signal_lineChartCurve2DPlotorGuideLineSelectRemove, this, [this]()
                {   
                    if (!this->isVisible())
                        return;
                    QVector<LineChartStraightLine*> selectLineArray;
                    for (auto lineChartStraightLine : m_lineArray)
                    {
                        if (lineChartStraightLine->selected())
                        {
                            selectLineArray.append(lineChartStraightLine);
                        }
                    }
                    slot_exitAddMarkerState();
                    m_isShowPreviewTracer = false;
                    m_previewTracer->setVisible(false);
                    for (auto lineChartStraightLine : selectLineArray)
                    {
                        this->removeItem(lineChartStraightLine);
                        m_lineArray.removeOne(lineChartStraightLine);
                    }
                    this->replot();
                });


            connect(IWidgetSignalInstance, &BaseWidget::IWidgetSignal::signal_lineChartCurve2DPlotorGuideLineAllRemove, this, [this]()
                    {
                        if (!this->isVisible())
                            return;
                        slot_exitAddMarkerState();
                        m_isShowPreviewTracer = false;
                        m_previewTracer->setVisible(false);
                        for (auto lineChartStraightLine : m_lineArray)
                        {
                            this->removeItem(lineChartStraightLine);
                        }
                        m_lineArray.clear();
                        this->replot(); 
                    });

            
            connect(IWidgetSignalInstance, &BaseWidget::IWidgetSignal::signal_lineChartCurve2DPlotorMarkerSelectRemove, this, [this]()
                {
                        if (!this->isVisible())
                            return;
                        QList<LineChartTracer*> selectTracerList;
                        for (auto selectItem : this->selectedItems())
                        {
                            LineChartTracer* selectTracer = qobject_cast<LineChartTracer*>(selectItem);
                            if (selectTracer != nullptr)
                            {
                                selectTracerList.append(selectTracer);
                            }
                        }
                        slot_exitAddMarkerState();
                        m_isShowPreviewTracer = false;
                        m_previewTracer->setVisible(false);
                        emit signal_removeSelectedTracer(selectTracerList);
                });

            
            
            connect(IWidgetSignalInstance, &BaseWidget::IWidgetSignal::signal_lineChartCurve2DPlotorMarkerAllRemove, this, [this]()
                    {
                        if (!this->isVisible())
                            return;
                        QList<LineChartTracer*> tracerList;
                        for (int i = 0; i < this->itemCount(); ++i)
                        {
                            LineChartTracer* tracer = qobject_cast<LineChartTracer*>(this->item(i));
                            if (tracer != nullptr && tracer != m_previewTracer)
                            {
                                tracerList.append(tracer);
                            }
                        }
                        slot_exitAddMarkerState();
                        m_isShowPreviewTracer = false;
                        m_previewTracer->setVisible(false);
                        emit signal_removeAlldTracer(tracerList); 
                });


    }

    void Curve2DPlotor::setWindowTitleName(const QString& titleName)
    {
        auto* layout = qobject_cast<QCPLayoutGrid*>(this->plotLayout());
        auto* title = qobject_cast<QCPTextElement*>(layout->element(0, 0));
        if (!title) return;

        // 1. 修改文字
        title->setText(titleName);
    }

    void Curve2DPlotor::setXAxisTitleName(const QString& titleName)
    {
        if (this->xAxis == nullptr)
        {
            return;
        }
        this->xAxis->setLabel(titleName);
        this->replot();
    }

    void Curve2DPlotor::setXAxisFontFamily(const QString& family)
    {
        if (this->xAxis == nullptr)
        {
            return;
        }
        auto font = QFont(family, this->xAxis->labelFont().pointSize());
        this->xAxis->setLabelFont(font);
        this->replot();
    }

    void Curve2DPlotor::setXAxisFontSize(int size)
    {
        if (this->xAxis == nullptr)
        {
            return;
        }
        this->xAxis->setLabelFont(QFont(this->xAxis->labelFont().family(), size));
        this->xAxis->setSelectedLabelFont(QFont(this->xAxis->labelFont().family(), size));
        this->replot();
    }

    void Curve2DPlotor::setXAxisRangeMin(double min)
    {
        if (this->xAxis == nullptr)
        {
            return;
        }
        this->xAxis->setRangeLower(min);
        this->replot();
    }

    void Curve2DPlotor::setXAxisRangeMax(double max)
    {
        if (this->xAxis == nullptr)
        {
            return;
        }
        this->xAxis->setRangeUpper(max);
        this->replot();
    }

    void Curve2DPlotor::setXAxisRangeStep(double step)
    {
        if (this->xAxis == nullptr)
        {
            return;
        }
        if (step <= 0)
        {
            this->xAxis->setTicker(QSharedPointer<QCPAxisTicker>(new QCPAxisTicker()));
        }
        else
        {
            QSharedPointer<QCPAxisTickerFixed> fixed(QSharedPointer<QCPAxisTickerFixed>(new QCPAxisTickerFixed()));
            fixed->setTickStep(step);
            fixed->setScaleStrategy(QCPAxisTickerFixed::ScaleStrategy::ssNone);
            this->xAxis->setTicker(fixed);
        }
        this->replot();
    }

    void Curve2DPlotor::setYAxisTitleName(const QString& titleName)
    {
        if (this->yAxis == nullptr)
        {
            return;
        }
        this->yAxis->setLabel(titleName);
        this->replot();
    }

    void Curve2DPlotor::setYAxisFontFamily(const QString& family)
    {
        if (this->yAxis == nullptr)
        {
            return;
        }
        auto font = QFont(family, this->yAxis->labelFont().pointSize());
        this->yAxis->setLabelFont(font);
        this->replot();
    }

    void Curve2DPlotor::setYAxisFontSize(int size)
    {
        if (this->yAxis == nullptr)
        {
            return;
        }
        this->yAxis->setLabelFont(QFont(this->yAxis->labelFont().family(), size));
        this->yAxis->setSelectedLabelFont(QFont(this->xAxis->labelFont().family(), size));
        this->replot();
    }

    void Curve2DPlotor::setYAxisRangeMin(double min)
    {
        if (this->yAxis == nullptr)
        {
            return;
        }
        this->yAxis->setRangeLower(min);
        this->replot();
    }

    void Curve2DPlotor::setYAxisRangeMax(double max)
    {
        if (this->yAxis == nullptr)
        {
            return;
        }
        this->yAxis->setRangeUpper(max);
        this->replot();
    }

    void Curve2DPlotor::setYAxisRangeStep(double step)
    {
        if (this->yAxis == nullptr)
        {
            return;
        }
        if (step <= 0)
        {
            this->yAxis->setTicker(QSharedPointer<QCPAxisTicker>(new QCPAxisTicker()));
        }
        else
        {
            QSharedPointer<QCPAxisTickerFixed> fixed(QSharedPointer<QCPAxisTickerFixed>(new QCPAxisTickerFixed()));
            fixed->setTickStep(step);
            fixed->setScaleStrategy(QCPAxisTickerFixed::ScaleStrategy::ssNone);
            this->yAxis->setTicker(fixed);
            // this->yAxis->ticker()->setTickStepStrategy(QCPAxisTicker::TickStepStrategy::tssMeetTickCount);
            // this->yAxis->setTickStep(step);
        }
        this->replot();
    }

    void Curve2DPlotor::titleDoubleClick(QMouseEvent* event)
    {
        if ((this->xAxis == nullptr) || (this->yAxis == nullptr))
        {
            return;
        }
        Q_UNUSED(event)
        if (QCPTextElement* title = qobject_cast<QCPTextElement*>(sender()))
        {
            // Set the plot title by double clicking on it
            bool ok;
            QString newTitle = QInputDialog::getText(this, "QCustomPlot example", "New plot title:", QLineEdit::Normal, title->text(), &ok);
            if (ok)
            {
                title->setText(newTitle);
                this->replot();
            }
        }
    }

    bool Curve2DPlotor::eventFilter(QObject* watched, QEvent* event)
    {
        if (watched == this)
        {
            if (m_isShowPreviewTracer)
            {
                if (event->type() == QEvent::MouseButtonPress)
                {
                    auto e = dynamic_cast<QMouseEvent*>(event);
                    if (e != nullptr && e->button() == Qt::LeftButton && e->modifiers() == Qt::NoModifier)
                    {
                        emit signal_addTracer();
                    }
                    e->accept();
                    return true;
                }
                else if (event->type() == QEvent::KeyPress)
                {
                    auto e = dynamic_cast<QKeyEvent*>(event);
                    if (e != nullptr && e->key() == Qt::Key_Escape)
                    {
                        m_previewTracer->setVisible(false);
                        m_isShowPreviewTracer = false;
                        this->replot();
                        e->accept();
                        return true;
                    }
                }
            }
        }
        return false;
    }

    void Curve2DPlotor::axisLabelDoubleClick(QCPAxis* axis, QCPAxis::SelectablePart part)
    {
        if ((this->xAxis == nullptr) || (this->yAxis == nullptr))
        {
            return;
        }
        // Set an axis label by double clicking on it
        if (part == QCPAxis::spAxisLabel) // only react when the actual axis label is clicked, not tick label or axis backbone
        {
            bool ok;
            QString newLabel = QInputDialog::getText(this, "QCustomPlot example", "New axis label:", QLineEdit::Normal, axis->label(), &ok);
            if (ok)
            {
                axis->setLabel(newLabel);
                this->replot();
            }
        }
    }

    void Curve2DPlotor::legendDoubleClick(QCPLegend* legend, QCPAbstractLegendItem* item)
    {
        if ((this->xAxis == nullptr) || (this->yAxis == nullptr))
        {
            return;
        }
        // Rename a graph by double clicking on its legend item
        Q_UNUSED(legend)
        if (item) // only react if item was clicked (user could have clicked on border padding of legend where there is no item, then item is 0)
        {
            QCPPlottableLegendItem* plItem = qobject_cast<QCPPlottableLegendItem*>(item);
            bool ok;
            QString newName = QInputDialog::getText(this, "QCustomPlot example", "New graph name:", QLineEdit::Normal, plItem->plottable()->name(), &ok);
            if (ok)
            {
                plItem->plottable()->setName(newName);
                this->replot();
            }
        }
    }

    void Curve2DPlotor::selectionChanged()
    {
        if ((this->xAxis == nullptr) || (this->yAxis == nullptr))
        {
            return;
        }
        /*
         normally, axis base line, axis tick labels and axis labels are selectable separately, but we want
         the user only to be able to select the axis as a whole, so we tie the selected states of the tick labels
         and the axis base line together. However, the axis label shall be selectable individually.

         The selection state of the left and right axes shall be synchronized as well as the state of the
         bottom and top axes.

         Further, we want to synchronize the selection of the graphs with the selection state of the respective
         legend item belonging to that graph. So the user can select a graph by either clicking on the graph itself
         or on its legend item.
        */

        // make top and bottom axes be selected synchronously, and handle axis and tick labels as one selectable object:
        if (this->xAxis->selectedParts().testFlag(QCPAxis::spAxis) || this->xAxis->selectedParts().testFlag(QCPAxis::spTickLabels) ||
            this->xAxis2->selectedParts().testFlag(QCPAxis::spAxis) || this->xAxis2->selectedParts().testFlag(QCPAxis::spTickLabels))
        {
            this->xAxis2->setSelectedParts(QCPAxis::spAxis | QCPAxis::spTickLabels);
            this->xAxis->setSelectedParts(QCPAxis::spAxis | QCPAxis::spTickLabels);
        }
        // make left and right axes be selected synchronously, and handle axis and tick labels as one selectable object:
        if (this->yAxis->selectedParts().testFlag(QCPAxis::spAxis) || this->yAxis->selectedParts().testFlag(QCPAxis::spTickLabels) ||
            this->yAxis2->selectedParts().testFlag(QCPAxis::spAxis) || this->yAxis2->selectedParts().testFlag(QCPAxis::spTickLabels))
        {
            this->yAxis2->setSelectedParts(QCPAxis::spAxis | QCPAxis::spTickLabels);
            this->yAxis->setSelectedParts(QCPAxis::spAxis | QCPAxis::spTickLabels);
        }
        //// synchronize selection of graphs with selection of corresponding legend items:
        // for (int i = 0; i < this->graphCount(); ++i)
        //{
        //     QCPGraph* graph = this->graph(i);
        //     QCPPlottableLegendItem* item = this->legend->itemWithPlottable(graph);
        //     //if (item->selected() || graph->selected())
        //     //{
        //     //    item->setSelected(true);
        //     //    graph->setSelection(QCPDataSelection(graph->data()->dataRange()));
        //     //}
        // }
        // this->replot();
        emit signal_updateSelectedGraph();
    }

    void Curve2DPlotor::onGraphClicked(QCPAbstractPlottable* plottable, int dataIndex, QMouseEvent* event)
    {
        if (plottable)
        {
            QCPPlottableLegendItem* item = this->legend->itemWithPlottable(plottable);
            item->setSelected(plottable->selected());
            this->replot();
        }
    }
    // 处理图例点击事件
    void Curve2DPlotor::onLegendClicked(QCPLegend* legend, QCPAbstractLegendItem* item, QMouseEvent* event)
    {
        if (!item)
            return;
        auto legendItem = qobject_cast<QCPPlottableLegendItem*>(item);
        if (legendItem == nullptr)
        {
            return;
        }
        QCPGraph* graph = qobject_cast<QCPGraph*>(legendItem->plottable());
        if (legendItem->selected())
        {
            graph->setSelection(QCPDataSelection(graph->data()->dataRange()));
        }
        else
        {
            QCPDataSelection s;
            graph->setSelection(s);
        }
        emit signal_updateSelectedGraph();
        this->replot();
    }

    void Curve2DPlotor::slot_mousePress()
    {
        if ((this->xAxis == nullptr) || (this->yAxis == nullptr))
        {
            return;
        }
        // if an axis is selected, only allow the direction of that axis to be dragged
        // if no axis is selected, both directions may be dragged

        if (this->xAxis->selectedParts().testFlag(QCPAxis::spAxis))
            this->axisRect()->setRangeDrag(this->xAxis->orientation());
        else if (this->yAxis->selectedParts().testFlag(QCPAxis::spAxis))
            this->axisRect()->setRangeDrag(this->yAxis->orientation());
        else
            this->axisRect()->setRangeDrag(Qt::Horizontal | Qt::Vertical);
    }

    void Curve2DPlotor::mouseWheel()
    {
        if ((this->xAxis == nullptr) || (this->yAxis == nullptr))
        {
            return;
        }
        // if an axis is selected, only allow the direction of that axis to be zoomed
        // if no axis is selected, both directions may be zoomed

        if (this->xAxis->selectedParts().testFlag(QCPAxis::spAxis))
            this->axisRect()->setRangeZoom(this->xAxis->orientation());
        else if (this->yAxis->selectedParts().testFlag(QCPAxis::spAxis))
            this->axisRect()->setRangeZoom(this->yAxis->orientation());
        else
            this->axisRect()->setRangeZoom(Qt::Horizontal | Qt::Vertical);
    }

    void Curve2DPlotor::addRandomGraph()
    {
        if ((this->xAxis == nullptr) || (this->yAxis == nullptr))
        {
            return;
        }
        int n = 50; // number of points in graph
        double xScale = (std::rand() / (double)RAND_MAX + 0.5) * 2;
        double yScale = (std::rand() / (double)RAND_MAX + 0.5) * 2;
        double xOffset = (std::rand() / (double)RAND_MAX - 0.5) * 4;
        double yOffset = (std::rand() / (double)RAND_MAX - 0.5) * 10;
        double r1 = (std::rand() / (double)RAND_MAX - 0.5) * 2;
        double r2 = (std::rand() / (double)RAND_MAX - 0.5) * 2;
        double r3 = (std::rand() / (double)RAND_MAX - 0.5) * 2;
        double r4 = (std::rand() / (double)RAND_MAX - 0.5) * 2;
        QVector<double> x(n), y(n);
        for (int i = 0; i < n; i++)
        {
            x[i] = (i / (double)n - 0.5) * 10.0 * xScale + xOffset;
            y[i] = (qSin(x[i] * r1 * 5) * qSin(qCos(x[i] * r2) * r4 * 3) + r3 * qCos(qSin(x[i]) * r4 * 2)) * yScale + yOffset;
        }

        this->addGraph();
        this->graph()->setName(QString("曲线 %1").arg(this->graphCount() - 1));
        this->graph()->setData(x, y);
        this->graph()->setLineStyle((QCPGraph::LineStyle)(std::rand() % 5 + 1));
        if (std::rand() % 100 > 50)
            this->graph()->setScatterStyle(QCPScatterStyle((QCPScatterStyle::ScatterShape)(std::rand() % 14 + 1)));
        QPen graphPen;
        graphPen.setColor(QColor(std::rand() % 245 + 10, std::rand() % 245 + 10, std::rand() % 245 + 10));
        graphPen.setWidthF(std::rand() / (double)RAND_MAX * 2 + 1);
        this->graph()->setPen(graphPen);
        this->replot();
    }

    void Curve2DPlotor::removeSelectedGraph()
    {
        m_isShowPreviewTracer = false;
        m_previewTracer->setVisible(false);
        if (m_polarAxisAngular)
        {
            emit signal_removeSelectedGraph();
            return;
        }

        if ((this->xAxis == nullptr) || (this->yAxis == nullptr))
        {
            return;
        }
        // if (this->selectedGraphs().size() > 0)
        //{
        //     //先移除侧边栏项目
        //     //emit signal_removeSelectedGraph(this->selectedGraphs());
        //     for (auto i : this->selectedGraphs())
        //     {
        //         this->removeGraph(i);
        //     }
        //     //this->removeGraph(this->selectedGraphs().first());
        //     this->replot();
        // }
        slot_exitAddMarkerState();
        emit signal_removeSelectedGraph();
    }

    void Curve2DPlotor::removeAllGraphs()
    {
        m_isShowPreviewTracer = false;
        m_previewTracer->setVisible(false);
        if (m_polarAxisAngular)
        {
            emit signal_removeAlldGraph();
            return;
        }

        if ((this->xAxis == nullptr) || (this->yAxis == nullptr))
        {
            return;
        }
        // this->clearGraphs();
        ////this->replot();
        // QList<QCPGraph*> graphList;
        // qDebug() << "this->graphCount() = " << this->graphCount();
        // for (int i = 0; i < this->graphCount(); ++i)
        //{
        //     QCPGraph* graph = this->graph(i);
        //     graph->setSelection(QCPDataSelection(graph->data()->dataRange()));

        //    qDebug() << "graph = " << graph;
        //    graphList.append(graph);
        //}

        slot_exitAddMarkerState();
        emit signal_removeAlldGraph();
    }

    void Curve2DPlotor::slot_exitAddMarkerState()
    {
        m_previewTracer->setVisible(false);
        m_isShowPreviewTracer = false;
        this->replot();
    }

    void Curve2DPlotor::removeMarkerAll()
    {
        QList<LineChartTracer*> tracerList;
        for (int i = 0; i < this->itemCount(); ++i)
        {
            LineChartTracer* tracer = qobject_cast<LineChartTracer*>(this->item(i));
            if (tracer != nullptr && tracer != m_previewTracer)
            {
                tracerList.append(tracer);
            }
        }
        if (!tracerList.isEmpty())
        {
            
            slot_exitAddMarkerState();
            m_isShowPreviewTracer = false;
            m_previewTracer->setVisible(false);
            emit signal_removeAlldTracer(tracerList); 
                        
            QString _pyCode = QString("PostProcessing.lineChartCurve2DPlotorMarkerAllRemove()");
            emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false); 
        }
    }

    void Curve2DPlotor::removeMarkerSelect()
    {
        QList<LineChartTracer*> selectTracerList;
        for (auto selectItem : this->selectedItems())
        {
            LineChartTracer* selectTracer = qobject_cast<LineChartTracer*>(selectItem);
            if (selectTracer != nullptr)
            {
                selectTracerList.append(selectTracer);
            }
        }
        if (!selectTracerList.isEmpty())
        {
            QString _pyCode = QString("PostProcessing.lineChartCurve2DPlotorMarkerSelectRemove()");
            emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
            slot_exitAddMarkerState();
            m_isShowPreviewTracer = false;
            m_previewTracer->setVisible(false);
            emit signal_removeSelectedTracer(selectTracerList);
        }

    }

    
    void Curve2DPlotor::enableTracer() {
        m_isShowPreviewTracer = true;
    }
    void Curve2DPlotor::disableTracer() {
        m_previewTracer->setVisible(false);
        m_isShowPreviewTracer = false;
        this->replot();
    }

    void Curve2DPlotor::contextMenuRequest(QPoint pos)
    {
        if ((!this->xAxis || !this->yAxis) && !m_polarAxisAngular)
        {
            return;
        }

        QMenu* menu = new QMenu(this);
        menu->setAttribute(Qt::WA_DeleteOnClose);

        auto lmd_popMenu = [menu, &pos, this]()
        {
            menu->popup(this->mapToGlobal(pos));
        };

        if (this->legend->selectTest(pos, false) >= 0) // context menu on legend requested
        {
            if (!m_polarAxisAngular)//极坐标禁用
            {
                menu->addAction("移至左上角", this, SLOT(moveLegend()))->setData((int)(Qt::AlignTop | Qt::AlignLeft));
                menu->addAction("移至上中间", this, SLOT(moveLegend()))->setData((int)(Qt::AlignTop | Qt::AlignHCenter));
                menu->addAction("移至右上角", this, SLOT(moveLegend()))->setData((int)(Qt::AlignTop | Qt::AlignRight));
                menu->addAction("移至右下角", this, SLOT(moveLegend()))->setData((int)(Qt::AlignBottom | Qt::AlignRight));
                menu->addAction("移至左下角", this, SLOT(moveLegend()))->setData((int)(Qt::AlignBottom | Qt::AlignLeft));
                lmd_popMenu();
                return;
            }
        }

        // if (m_polarAxisAngular) {
        //     contextMenuRequest4PolarGraph(pos, menu);
        //     lmd_popMenu();
        //     return;
        // }

        if (!m_isShowPreviewTracer)
        {
            do
            {
                if (m_polarAxisAngular)
                {
                    if (m_polarAxisAngular->getGraphList().isEmpty())
                    {
                        break;
                    }
                }
                else
                {
                    if (this->plottableCount() == 0)
                    {
                        break;
                    }
                }
                menu->addAction(tr("添加标记"), this, [this]()
                                { m_isShowPreviewTracer = true; });
            } while (0);
        }

        // if (this->plottableCount() > 0 && !m_isShowPreviewTracer) {
        //     menu->addAction(tr("添加标记"), this, [this]() {
        //         m_isShowPreviewTracer = true;
        //         });
        // }
        if (m_isShowPreviewTracer)
        {
            menu->addAction(tr("退出标记模式"), this, [this]()
                            {
                m_previewTracer->setVisible(false);
                m_isShowPreviewTracer = false;
                this->replot(); });
        }
        if (this->selectedItems().size() > 0)
        {
            QList<LineChartTracer*> selectTracerList;
            for (auto selectItem : this->selectedItems())
            {
                LineChartTracer* selectTracer = qobject_cast<LineChartTracer*>(selectItem);
                if (selectTracer != nullptr)
                {
                    selectTracerList.append(selectTracer);
                }
            }
            if (!selectTracerList.isEmpty())
            {
                menu->addAction(tr("删除选中标记"), this, [this, selectTracerList]()
                                { 
                        
                        QString _pyCode = QString("PostProcessing.lineChartCurve2DPlotorMarkerSelectRemove()");
                        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
                        slot_exitAddMarkerState();
                        m_isShowPreviewTracer = false;
                        m_previewTracer->setVisible(false);
                        emit signal_removeSelectedTracer(selectTracerList);
                        
                    });
            }
        }
        
        if (this->itemCount() > 0)
        {
            QList<LineChartTracer*> tracerList;
            for (int i = 0; i < this->itemCount(); ++i)
            {
                LineChartTracer* tracer = qobject_cast<LineChartTracer*>(this->item(i));
                if (tracer != nullptr && tracer != m_previewTracer)
                {
                    tracerList.append(tracer);
                }
            }
            if (!tracerList.isEmpty())
            {
                menu->addAction(tr("删除所有标记"), this, [this, tracerList]()
                                {
                        slot_exitAddMarkerState();
                        m_isShowPreviewTracer = false;
                        m_previewTracer->setVisible(false);
                        emit signal_removeAlldTracer(tracerList); 
                        
                        QString _pyCode = QString("PostProcessing.lineChartCurve2DPlotorMarkerAllRemove()");
                        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
                    });
                
            }
            
        }

        // menu->addAction("Add random graph", this, SLOT(addRandomGraph()));
        if (m_polarAxisAngular)
        {
            const QList<QCPPolarGraph*>& graphList = m_polarAxisAngular->getGraphList();
            bool hasSelectedGraph = std::any_of(graphList.begin(), graphList.end(), [](QCPPolarGraph* graph)
                                                {
                PolarGraph* polarGraph = qobject_cast<PolarGraph*>(graph);
                return polarGraph ? polarGraph->isSelected() : graph->selected(); });
            if (hasSelectedGraph)
            {
                menu->addAction("删除选择的曲线", this, [this]()
                    { 
                        QString _pyCode = QString("PostProcessing.lineChartCurve2DPlotorRemoveSelectedGraph()");
                        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
                        removeSelectedGraph();
                    });
            }

            if (!graphList.isEmpty())
            {
                menu->addAction("删除所有曲线", this, [this]()
                                { 
                        QString _pyCode = QString("PostProcessing.lineChartCurve2DPlotorRemoveAllGraphs()");
                        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
                        removeAllGraphs();
                    });
            }
            int selectNumber = 0;
            for (auto graph : graphList)
            {
                PolarGraph* polarGraph = qobject_cast<PolarGraph*>(graph);
                if (polarGraph->isSelected())
                {
                    ++selectNumber;
                }
            }
            if (selectNumber == 1)
            {
                menu->addAction("重命名", this, &Curve2DPlotor::signal_renameGraph);
            }
        }
        else
        {
            if (this->selectedGraphs().size() > 0)
            {
                menu->addAction("删除选择的曲线", this, [this]()
                                { 
                        QString _pyCode = QString("PostProcessing.lineChartCurve2DPlotorRemoveSelectedGraph()");
                        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
                        removeSelectedGraph(); });
            }
            if (this->graphCount() > 0)
            {
                menu->addAction("删除所有曲线", this, [this]()
                                { 
                        QString _pyCode = QString("PostProcessing.lineChartCurve2DPlotorRemoveAllGraphs()");
                        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
                        removeAllGraphs(); });
            }
            if (this->graphCount() > 0)
            {
                menu->addAction(tr("添加局部范围"), this, [this, pos]()
                                {
                        slot_exitAddMarkerState();
                        emit signal_showLocalScope();
                    });
                menu->addAction(tr("添加X轴参考线"), this, [this, pos]()
                                {
                        slot_exitAddMarkerState();
                        m_isShowPreviewTracer = false;
                        m_previewTracer->setVisible(false);
                    auto xLine = new LineChartStraightLine(this, LineChartStraightLine::XAxis);
                    xLine->XAxisLineUpdate(this->xAxis->range().center());
                    xLine->updataStyle2DGuideLineProperty();
                    xLine->setLineChartStraightLineID(++m_lineChartStraightLineMaxID);

                    int typeAxis = static_cast<int>(LineChartStraightLine::XAxis);
                    QString _pyCode = QString("PostProcessing.lineChartCreateLineChartStraightLine(%1)").arg(typeAxis);
                    emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
                    m_lineArray.append(xLine);
                    this->replot(); });
                menu->addAction(tr("添加Y轴参考线"), this, [this, pos]()
                                {
                        slot_exitAddMarkerState();
                        m_isShowPreviewTracer = false;
                        m_previewTracer->setVisible(false);
                auto yLine = new LineChartStraightLine(this, LineChartStraightLine::YAxis);
                yLine->YAxisLineUpdate(this->yAxis->range().center());
                yLine->updataStyle2DGuideLineProperty();
                yLine->setLineChartStraightLineID(++m_lineChartStraightLineMaxID);

                int typeAxis = static_cast<int>(LineChartStraightLine::YAxis);
                QString _pyCode = QString("PostProcessing.lineChartCreateLineChartStraightLine(%1)").arg(typeAxis);
                emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);

                m_lineArray.append(yLine);
                this->replot(); });
                //if (!m_lineArray.isEmpty())
                //{
                //    QVector<LineChartStraightLine*> selectLineArray;
                //    for (auto lineChartStraightLine : m_lineArray)
                //    {
                //        if (lineChartStraightLine->selected())
                //        {
                //            selectLineArray.append(lineChartStraightLine);
                //        }
                //    }
                //    if (!selectLineArray.isEmpty())
                //    {
                //        menu->addAction(tr("删除选择的参考线"), this, [this, selectLineArray]()
                //                        {
                //                slot_exitAddMarkerState();
                //                m_isShowPreviewTracer = false;
                //                m_previewTracer->setVisible(false);
                //        for (auto lineChartStraightLine : selectLineArray) {
                //            this->removeItem(lineChartStraightLine);
                //            m_lineArray.removeOne(lineChartStraightLine);
                //        }
                //        this->replot(); });
                //    }
                //    menu->addAction(tr("删除所有参考线"), this, [this]()
                //                    {
                //            slot_exitAddMarkerState();
                //            m_isShowPreviewTracer = false;
                //            m_previewTracer->setVisible(false);
                //    for (auto lineChartStraightLine : m_lineArray) {
                //        this->removeItem(lineChartStraightLine);
                //    }
                //    m_lineArray.clear();
                //    this->replot(); });
                //}
            }
            if (!m_lineArray.isEmpty())
            {
                QVector<LineChartStraightLine*> selectLineArray;
                for (auto lineChartStraightLine : m_lineArray)
                {
                    if (lineChartStraightLine->selected())
                    {
                        selectLineArray.append(lineChartStraightLine);
                    }
                }
                if (!selectLineArray.isEmpty())
                {
                    menu->addAction(tr("删除选择的参考线"), this, [this, selectLineArray]()
                            {
                            QString _pyCode = QString("PostProcessing.lineChartCurve2DPlotorGuideLineSelectRemove()");
                            emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
                            slot_exitAddMarkerState();
                            m_isShowPreviewTracer = false;
                            m_previewTracer->setVisible(false);
                            for (auto lineChartStraightLine : selectLineArray)
                            {
                                this->removeItem(lineChartStraightLine);
                                m_lineArray.removeOne(lineChartStraightLine);
                            }
                            this->replot(); 
                            
                        });
                }
                menu->addAction(tr("删除所有参考线"), this, [this]()
                    {
                        slot_exitAddMarkerState();
                        m_isShowPreviewTracer = false;
                        m_previewTracer->setVisible(false);
                        for (auto lineChartStraightLine : m_lineArray)
                        {
                            this->removeItem(lineChartStraightLine);
                        }
                        m_lineArray.clear();
                        this->replot(); 
                        
                        QString _pyCode = QString("PostProcessing.lineChartCurve2DPlotorGuideLineAllRemove()");
                        emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
                    });
            }

            if (this->selectedGraphs().size() == 1)
            {
                menu->addAction("重命名", this, &Curve2DPlotor::signal_renameGraph);
            }
            if (this->selectedGraphs().size() > 0)
            {
                menu->addAction("复制", this, &Curve2DPlotor::signal_copyGraph);
            }
            if (infoListCopy != nullptr)
            {
                QList<Info2DPointer> infoListCopyValue = *infoListCopy;
                if (!infoListCopyValue.isEmpty())
                {
                    menu->addAction("粘贴", this, &Curve2DPlotor::signal_pasteGraph);
                }
            }
        }

        QAction* exportMarkDataAction = menu->addAction("导出标记数据", this, &Curve2DPlotor::signal_exportMarkerData); // 极坐标，二维折线图，二维热力图
        exportMarkDataAction->setEnabled(false);
        for (int i = 0; i < this->itemCount(); ++i)
        {
            LineChartTracer* tracer = qobject_cast<LineChartTracer*>(this->item(i));
            if (tracer != nullptr && tracer != m_previewTracer)
            {
                exportMarkDataAction->setEnabled(true);
                break;
            }
        }

        lmd_popMenu();
    }

    void Curve2DPlotor::moveLegend()
    {
        if ((this->xAxis != nullptr) && (this->yAxis != nullptr))
        {
            if (QAction* contextAction = qobject_cast<QAction*>(sender())) // make sure this slot is really called by a context menu action, so it carries the data we need
            {
                bool ok;
                int dataInt = contextAction->data().toInt(&ok);
                if (ok)
                {
                    QString _pyCode = QString("PostProcessing.lineChartCenterWidgetMoveLegend(%1)")
                                          .arg(dataInt);
                    emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);
                    this->axisRect()->insetLayout()->setInsetAlignment(0, (Qt::Alignment)dataInt);
                    this->replot();
                }
            }
        }

        if (m_polarAxisAngular)
        {
            this->plotLayout()->addElement(0, 0, legend);   // 左上角
        }
    }

    void Curve2DPlotor::graphClicked(QCPAbstractPlottable* plottable, int dataIndex)
    {
        if ((this->xAxis == nullptr) || (this->yAxis == nullptr))
        {
            return;
        }
        // return;
        //  since we know we only have QCPGraphs in the plot, we can immediately access interface1D()
        //  usually it's better to first check whether interface1D() returns non-zero, and only then use it.
        double dataValue = plottable->interface1D()->dataMainValue(dataIndex);
        QString message = QString("点击了图形 '%1' 在数据点 #%2 值为 %3.").arg(plottable->name()).arg(dataIndex).arg(dataValue);
        // ui->statusBar->showMessage(message, 2500);
        // QMessageBar::success(ElaMessageBarType::PositionPolicy::BottomLeft, "提示", message, 1000, this);
    }

    LineChartStraightLine* Curve2DPlotor::getLineChartStraightLineByID(int lineID)
    {
        for (auto _line : m_lineArray)
        {
            if (_line->getLineChartStraightLineID() == lineID)
                return _line;
        }
    }

    QDomElement& Curve2DPlotor::writeToProjectFile(QDomDocument* doc, QDomElement* element, bool isdiso)
    {
        QDomElement _Curve2DPlotorRoot = doc->createElement("Curve2DPlotor");
        QDomAttr idattr = doc->createAttribute("ID");
        idattr.setValue(QString::number(1));
        _Curve2DPlotorRoot.setAttributeNode(idattr);
        QDomAttr LineChartStraightLineMaxIDattr = doc->createAttribute("LineChartStraightLineMaxID");
        LineChartStraightLineMaxIDattr.setValue(QString::number(m_lineChartStraightLineMaxID));
        _Curve2DPlotorRoot.setAttributeNode(LineChartStraightLineMaxIDattr);

        for (auto _line : m_lineArray)
        {
            _line->writeToProjectFile(doc, &_Curve2DPlotorRoot, isdiso);
        }

        element->appendChild(_Curve2DPlotorRoot);

        return _Curve2DPlotorRoot;
    }

    void Curve2DPlotor::readFromProjectFile(QDomElement* element, bool isdiso)
    {
        int id = element->attribute("ID").toInt();
        m_lineChartStraightLineMaxID = element->attribute("LineChartStraightLineMaxID").toInt();
        auto _LineChartStraightLineEle = element->elementsByTagName("LineChartStraightLine");

        auto _LineCount = _LineChartStraightLineEle.count();
        if (_LineCount == 0)
            return;
        for (int i = 0; i < _LineCount; i++)
        {
            QDomElement _elemModel = _LineChartStraightLineEle.at(i).toElement();
            auto _LineChartStraightLineType = _elemModel.attribute("LineChartStraightLineType");
            LineChartStraightLine::Type _lineType = LineChartStraightLine::Type::XAxis;
            if (_LineChartStraightLineType == "XAxis")
            {
                _lineType = LineChartStraightLine::Type::XAxis;
            }
            else if (_LineChartStraightLineType == "YAxis")
            {
                _lineType = LineChartStraightLine::Type::YAxis;
            }

            auto _Line = new LineChartStraightLine(this, _lineType);
            _Line->readFromProjectFile(&_elemModel, isdiso);
            m_lineArray.append(_Line);
            auto _tmpProperty = _Line->getStyle2DGuideLineProperty();
            _Line->SetValue(_tmpProperty->m_value);
            auto penLine = _Line->pen();
            penLine.setStyle(Qt::PenStyle(_tmpProperty->m_guideLineStyle + 1));
            penLine.setWidthF(_tmpProperty->m_guideLineThickness);
            penLine.setColor(_tmpProperty->m_guideLineColor);
            _Line->setPen(penLine);

            this->replot(); 
        }


    }
} // namespace pst
